import { ElMessage } from 'element-plus'
import { useMenuStore } from '@/store/menu/index.js'
import router from './index.js'

const whiteList = ['/login']
router.beforeEach(async (to, from, next) => {
    const token = localStorage.getItem('token')
    const hasroutes = useMenuStore().hasroutes
    if (token) {
        if (to.path == '/login') {
            next('/home')
            return
        }
        else {
            console.log("has", hasroutes)
            if (!hasroutes) {
                await useMenuStore().loadAuthRouters()
                const menuList = useMenuStore().menuList
                bindRoute(menuList)
                useMenuStore().setHasroutes(true)
                next({ ...to, replace: true })
                return
            }
            next()
        }
    }
    else {
        if (whiteList.includes(to.path)) {
            next()
        }
        else {
            ElMessage.error("请登录")
            next('/login')
        }
    }
})



const bindRoute = (menuList) => {

    let newRoutes = router.options.routes
    menuList.forEach(menu => {
        treeMenu(menu, newRoutes)
    })
    newRoutes.forEach(route => {
        router.addRoute(route)
    })
}

const treeMenu = (menus, newRoutes) => {
    if (menus.children.length != 0) {
        menus.children.forEach(m => {
            treeMenu(m, newRoutes)
        })
    }
    else {
        let route = menuToRoute(menus)
        if (route) {
            newRoutes[1].children.push(route)
        }
    }
}


const menuToRoute = (menu) => {
    const modules = import.meta.glob('@/**/*.vue')
    if (!menu.component) {
        return null
    }
    let route = {
        name: menu.menuName,
        path: menu.path,
        component: modules[`/src/${menu.component}`]
    }
    return route
}
